package com.vmc.strategy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.vmc.exception.VMCException;
import com.vmc.model.AbstractTransferDetail;
import com.vmc.model.DownloadTransferProperties;
import com.vmc.util.GlobalStorageUtility;

public class RenameTransferAction extends AbstractAction<File> {

	public static String NEW = "_NEW_";
	
	@Override
	boolean performMainAction(File actionableItem) throws VMCException {
		
		List<AbstractTransferDetail> details = GlobalStorageUtility.getInstance().getCopiedFiles();
		if (details != null) {
			List<File> copyList = new ArrayList<File>();
			
			for (AbstractTransferDetail detail : details) {
				File file = new File(detail.getDestinationFilePath());
				if (file.exists() && file.isFile()) {
					copyList.add(file);
				}
			}
			
			this.renameNewFiles(copyList);
		}
		
		return false;
	}

	private void renameNewFiles(List<File> fileList) {
		if (fileList != null) {
			List<File> parentFileList = new ArrayList<File>();
			for (File file : fileList) {
				if (this.isRoot(file) || file.getName().contains(NEW)) {
					continue;
				}
				file.renameTo(new File(file.getParentFile().getAbsolutePath() + File.separator +  NEW + file.getName()));
				parentFileList.add(file.getParentFile());
			}
			if (parentFileList != null && parentFileList.size() > 0) {
				renameNewFiles(parentFileList);
			}
		}
	}
	
	private boolean isRoot(File file) {
		if (file != null) {
			DownloadTransferProperties properties = GlobalStorageUtility.getInstance().getProperties();
			if (properties != null) {
				if (file.getAbsolutePath().equalsIgnoreCase(new File(properties.getMovieDestinationRootPath()).getAbsolutePath()) ||
						file.getAbsolutePath().equalsIgnoreCase(new File(properties.getTvDestinationRootPath()).getAbsolutePath())) {
					return true;
				}
			}
		}
		
		return false;
	}
}
